package cn.edu.zafu.bigdata.lekang.shiyan8;

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建服务器端套接字，监听端口号
            ServerSocket serverSocket = new ServerSocket(1234);
            System.out.println("Server is running and waiting for client connection...");

            // 服务器无限循环，等待客户端连接
            while (true) {
                // 等待接受客户端连接，此方法会阻塞，直到一个连接建立
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");

                // 使用socket的输入流读取客户端发送的消息
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // 使用socket的输出流发送消息给客户端
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                // 读取客户端发送的消息
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Client says: " + inputLine);

                    // 将消息回复给客户端
                    out.println("Server received your message: " + inputLine);

                    // 如果客户端发送"bye"，则结束会话
                    if ("bye".equalsIgnoreCase(inputLine)) {
                        break;
                    }
                }

                // 关闭连接
                in.close();
                out.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
